<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
        <el-form-item label="客户名称" prop="title1" label-width="100px">
          <el-input v-model="queryParams.title1" placeholder="请输入客户名称" clearable style="width: 240px"
            @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
        </el-form-item>
        <el-form-item label="询价单名称" prop="title2" label-width="100px">
          <el-input v-model="queryParams.title2" placeholder="请输入询价单名称" clearable style="width: 240px"
            @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
        </el-form-item>
        <el-form-item label="询价单编号" prop="title3" label-width="100px">
          <el-input v-model="queryParams.title3" placeholder="请输入询价单编号" clearable style="width: 240px"
            @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <!-- 表格数据 -->
      <el-table v-loading="loading" size="large" :data="roleList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="index" label="序号" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="cumtomName" width="300" />
        <el-table-column label="询价单名称" align="center" prop="queryContent" width="300" />
        <el-table-column label="询价单编号" align="center" prop="queryCode" width="150" />
        <el-table-column label="保存时间" align="center" prop="queryCode" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" min-width="160px" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">询价报价</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </div>
  </template>
  
  <script setup name="Role">
  import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
  import { useInfoStore } from '@/store/modules/info.js'
  const userInfo = useInfoStore();
  
  const router = useRouter();
  const { proxy } = getCurrentInstance();
  // const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
  
  const roleList = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  
  
  const data = reactive({
    form: {
      tenantName: null,
      tenantDoMain: null,
      tenantDes: null,
      tenantOrders: 0,
      id: null
    },
    queryParams: {
      pageNo: 1,
      pageSize: 10,
      title1: null,
      title2: null,
      title3: null,
    },
    rules: {
      tenantName: [{ required: true, message: "系统名称不能为空", trigger: "blur" }],
      tenantDoMain: [{ required: true, message: "系统链接地址为空", trigger: "blur" }],
    },
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询角色列表 */
  function getList() {
    loading.value = true;
    proxy.quote_API.GetTemCachelist(queryParams.value).then(response => {
      roleList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  }
  // 输入时触发的防抖处理函数
  let timer = null;
  function handleInput() {
    clearTimeout(timer);
    timer = setTimeout(handleQuery, 300);
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNo = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  /** 删除按钮操作 */
  function handleDelete(row) {
    proxy.$modal.confirm('是否确认删除客户"' + row.cumtomName + '"的保存记录?').then(function () {
      proxy.quote_API.DeleteForCacheSave({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
    })
  }
  
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }
  
  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.roleId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  /** 角色状态修改 */
  function handleStatusChange(row) {
    let text = row.status === "0" ? "启用" : "停用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(function () {
      return changeRoleStatus(row.roleId, row.status);
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
  }
  
  /** 更多操作 */
  function handleCommand(command, row) {
    switch (command) {
      case "handleDataScope":
        handleDataScope(row);
        break;
      case "handleAuthUser":
        handleAuthUser(row);
        break;
      default:
        break;
    }
  }
  
  /** 分配用户 */
  function handleAuthUser(row) {
    router.push("/system/role-auth/user/" + row.roleId);
  }
  
  /** 查询菜单树结构 */
  function getMenuTreeselect() {
    menuTreeselect().then(response => {
      menuOptions.value = response.data;
    });
  }
  
  /** 所有部门节点数据 */
  function getDeptAllCheckedKeys() {
    // 目前被选中的部门节点
    let checkedKeys = deptRef.value.getCheckedKeys();
    // 半选中的部门节点
    let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }
  
  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    form.value = {
      tenantName: null,
      tenantDoMain: null,
      tenantDes: null,
      tenantOrders: 0,
      id: null
    };
    proxy.resetForm("roleRef");
  }
  
  /** 添加角色 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加系统";
  }
  
  /** 跳转 */
  function handleUpdate(row) {
    router.push({ 
      path: '/quoteSystem/inquire/quote',
      state: row
    });
  }
  
  /** 根据角色ID查询菜单树结构 */
  function getRoleMenuTreeselect(roleId) {
    return roleMenuTreeselect(roleId).then(response => {
      menuOptions.value = response.menus;
      return response;
    });
  }
  
  /** 根据角色ID查询部门树结构 */
  function getDeptTree(roleId) {
    return deptTreeSelect(roleId).then(response => {
      deptOptions.value = response.depts;
      return response;
    });
  }
  
  /** 树权限（展开/折叠）*/
  function handleCheckedTreeExpand(value, type) {
    if (type == "menu") {
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    } else if (type == "dept") {
      let treeList = deptOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    }
  }
  
  /** 树权限（全选/全不选） */
  function handleCheckedTreeNodeAll(value, type) {
    if (type == "menu") {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
    } else if (type == "dept") {
      deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
    }
  }
  
  /** 树权限（父子联动） */
  function handleCheckedTreeConnect(value, type) {
    if (type == "menu") {
      form.value.menuCheckStrictly = value ? true : false;
    } else if (type == "dept") {
      form.value.deptCheckStrictly = value ? true : false;
    }
  }
  
  /** 所有菜单节点数据 */
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }
  
  // 处理值变化的方法
  const handleChange = (value) => {
    if (Number.isInteger(value)) {
      if (value < 0) {
        form.value.tenantOrders = 0;
      } else if (value > 9) {
        form.value.tenantOrders = 9;
      }
    } else {
      // 如果不是整数，恢复到上一个有效值
      form.value.tenantOrders = Math.round(form.value.tenantOrders);
    }
  }
  
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.id) {
          EditTenant({
            ...form.value,
            uniqueKey: userInfo.info.uniqueKey
          }).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          AddTenant(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }
  // 复制
  async function copy(text) {
    console.log(text);
    try {
      await navigator.clipboard.writeText(text);
      proxy.$modal.msgSuccess('复制成功');
    } catch (err) {
      console.log(err);
  
    }
  }
  
  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }
  
  /** 选择角色权限范围触发 */
  function dataScopeSelectChange(value) {
    if (value !== "2") {
      deptRef.value.setCheckedKeys([]);
    }
  }
  
  /** 提交按钮（数据权限） */
  function submitDataScope() {
    if (form.value.roleId != undefined) {
      form.value.deptIds = getDeptAllCheckedKeys();
      dataScope(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openDataScope.value = false;
        getList();
      });
    }
  }
  
  /** 取消按钮（数据权限）*/
  function cancelDataScope() {
    openDataScope.value = false;
    reset();
  }
  getList();
  </script>
  